import React, { useRef, useState } from 'react';
import './VisualEditingPackage/vstyles/index.less';
import Menu from './VisualEditingPackage/components/Menu';
import Canvas from './VisualEditingPackage/components/Canvas';
import _ from 'lodash';

const VisualEditing = () => {
  const canvas = useRef(null);
  const [blocks, setBlocks] = useState([]);
  const onDrop = (e) => {
    const v_canvas = canvas.current;
    const distX = e.clientX - v_canvas.offsetLeft;
    const distY = e.clientY - v_canvas.offsetTop;
    const json_block = JSON.parse(e.dataTransfer.getData('Text'));
    const newData = [...blocks];
    const { width, height } = json_block;
    newData.push({
      ...json_block,
      style: {
        ...json_block.style,
        left: distX - width / 2,
        top: distY - height / 2,
      },
    });
    setBlocks(newData);
  };
  const onDragOver = (e) => {
    e.preventDefault();
  };
  const clearFocus = (data) => {
    return _.map(data, (item, key) => {
      return {
        ...item,
        focus: false,
      };
    });
  };
  const onMouseDown = () => {
    const newData = clearFocus(blocks);
    setBlocks(newData);
  };
  return (
    <div id="VisualEditing">
      <div className="menu">
        <Menu />
      </div>
      <div className="canvas" onMouseDown={onMouseDown} ref={canvas} onDrop={onDrop} onDragOver={onDragOver}>
        <Canvas data={blocks} setData={setBlocks} clearFocus={clearFocus} />
      </div>
      <div className="block-detail">block-detail</div>
    </div>
  );
};

export default VisualEditing;
